package ycl.scheduled.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ycl.scheduled.common.base.service.impl.BaseServiceImpl;
import ycl.scheduled.common.enums.ScheduledEnum;
import ycl.scheduled.common.models.req.scheduled.ScheduledCreateReq;
import ycl.scheduled.common.models.tencent.maps.req.SuggestionReq;
import ycl.scheduled.common.models.tencent.maps.res.BaseGpsQueryRes;
import ycl.scheduled.common.models.tencent.maps.res.SuggestionRes;
import ycl.scheduled.common.utils.BeanConvertUtil;
import ycl.scheduled.common.utils.DateTimeUtil;
import ycl.scheduled.entity.SysUserScheduled;
import ycl.scheduled.mapper.SysUserScheduledMapper;
import ycl.scheduled.service.GpsService;
import ycl.scheduled.service.SysUserScheduledService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户日程安排 服务实现类
 * </p>
 *
 * @author ycl
 * @since 2022-01-20 00:04:45
 */
@Service
public class SysUserScheduledServiceImpl
		extends BaseServiceImpl<SysUserScheduledMapper, SysUserScheduled>
		implements SysUserScheduledService {

	@Resource
	private SysUserScheduledMapper userScheduledMapper;
	@Resource
	private GpsService gpsService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void create(HttpServletRequest request, ScheduledCreateReq req) {
		Long userId = getLoginUserId(request);
		LocalDateTime expireTime = req.getExpireTime();
		SysUserScheduled scheduled = selectLatelyTimeDiffByUserId(request, expireTime);
		int i = verify(expireTime, scheduled.getExpireTime());
		Assert.isTrue(i != - 1, "您当前日期一个小时内已有日程，请合理安排时间");

		SysUserScheduled convert = BeanConvertUtil.convert(req, SysUserScheduled.class);
		convert.setCreateTime(LocalDateTime.now())
				.setUserId(userId)
				.setStatus(ScheduledEnum.ScheduledStatusEnum.NOT_STARTED.status);
		String address = req.getAddress();
		if (StrUtil.isNotBlank(address)) {
			//调用腾讯地图获取经纬度
			SuggestionReq suggestion = new SuggestionReq();
			suggestion.setKeyword(req.getAddress());
			suggestion.setLat(req.getLat())
					.setLng(req.getLng());
			BaseGpsQueryRes<SuggestionRes> suggestions = gpsService.getSuggestion(suggestion);
			SuggestionRes res = suggestions.getData().get(0);
			Assert.notNull(res, "未获取到您的地址, 请重新定位");

			convert.setLat(res.getLocation().getLat())
					.setLng(res.getLocation().getLng())
					.setAddress(res.getAddress());
		}

		System.out.println(JSONObject.toJSONString(convert));

		//userScheduledMapper.insert(convert);
	}


	/**
	 * 查询此日程日期的最近的日程, 有就判断时间
	 *
	 * @param request    用户登录信息
	 * @param expireTime 时间
	 * @return 日程
	 */
	private SysUserScheduled selectLatelyTimeDiffByUserId(HttpServletRequest request, LocalDateTime expireTime) {
		Assert.isTrue(expireTime.isAfter(LocalDateTime.now()), "创建或修改日程的时间不能在当前时间之前");
		Long userId = getLoginUserId(request);
		SysUserScheduled scheduled = userScheduledMapper.selectLatelyTimeDiffByUserId(userId, expireTime);
		if (scheduled == null) {
			return new SysUserScheduled();
		}
		return scheduled;
	}


	@Override
	public int verify(HttpServletRequest request, ScheduledCreateReq req) {
		LocalDateTime expireTime = req.getExpireTime();
		SysUserScheduled scheduled = selectLatelyTimeDiffByUserId(request, expireTime);
		return verify(expireTime, scheduled.getExpireTime());
	}


	/**
	 * 校验
	 *
	 * @param htmlExpireTime
	 * @param sqlExpireTime
	 * @return
	 */
	private int verify(@NotNull(message = "前端时间传参不正确")
			                   LocalDateTime htmlExpireTime,
	                   LocalDateTime sqlExpireTime) {

		if (sqlExpireTime == null)
			return 1;

		int diff = DateTimeUtil.getTimeDiff(htmlExpireTime, sqlExpireTime, TimeUnit.MINUTES);
		if (diff < 60)
			return - 1;
		else if (diff < 90)
			return 0;
		else
			return 1;
	}
}
